<template>
  <view class="page">
    <!-- topbar start -->
    <view class="cu-custom bg-white" :style="[{ height: CustomBar + 'px', paddingTop: StatusBar + 'px' }]">
      <view class="cu-bar bg-white fixed" :style="[{ height: CustomBar + 'px', paddingTop: StatusBar + 'px' }]">
        <view class="action" @click="back"><text class="cuIcon-back fu-fs36"></text></view>
        <view class="fu-fs32">{{i18n['选择位置']}}</view>
        <!-- #ifdef APP-PLUS || H5 -->
        <view class="margin-right " @click="back"> {{i18n['确定']}}</view>
        <!-- #endif -->
      </view>
    </view>
    <!-- #ifdef MP -->
    <view class="tool-box text-right padding-sm" :style="{ top: CustomBar + 'px' }">
      <view class="cu-btn text-sm" @tap="back"> {{i18n['确定']}}</view>
    </view>
    <!-- #endif -->
    <!-- topbar end -->
    <view class="select_location ">
      <view class="cell flex">
        <text class="title"> {{i18n['当前选择']}}</text>
        <view class="flex flex-sub">
          <input class="flex-sub" type="text" disabled v-model="address" :placeholder="i18n['请选择自取点']" />
          <text class="margin-right cuIcon-locationfill text-gray" style="font-size: 40rpx; " @click="getLocation"></text>
        </view>
      </view>
    </view>
    <!--    标题栏 end -->
    <!--    左侧分类 start -->
    <!-- #ifdef MP-->
    <view :style="{height: 'calc(100% - '+(CustomBar+ CustomBar )+'px)'}" class="content">
    <!-- #endif -->
    <!-- #ifdef APP-PLUS || H5 -->
    <view :style="{height: 'calc(100% - '+(CustomBar)+'px)'}" class="content">
    <!-- #endif -->
      <scroll-view class="left" scroll-y>
        <block v-for="(item,index) in lists" :key="index">
          <view class="item-wrap" :class="{'prev-wrap':index == currentIndex-1,'next-wrap':index == currentIndex+1}">
            <view class="item text-center text-cut" :class="{'active ': index == currentIndex,'prev':index == currentIndex-1,'next':index == currentIndex+1}"
              @click="handleSelect(item,index)">
              {{ item.name }}
            </view>
          </view>
        </block>
      </scroll-view>
      <!-- 左侧分类 end -->
      <!-- 右侧分类 start-->
      <view class="right">
        <picker-view v-if="inviteSome.length > 0" @change="bindChange" class="picker-view">
          <picker-view-column>
            <view class="picker_item" v-for="(item,index) in inviteSome" :key="index">{{item.deliver_name}}</view>
          </picker-view-column>
        </picker-view>
        <view v-else class="page-kong padding-tb">
          <view class="block-262">
            <image :src="imgWechatUrl+'/empty/order.png'" mode="aspectFill"></image>
          </view>
          <view style="width:100%;text-align: center;margin-top: 50rpx;" class="margin-top-sm  text-999">{{i18n['该地区还没有自取点']}}</view>
        </view>

      </view>
      <!-- 右侧分类 end -->
    </view>
    <!-- 断网监测 start-->
    <fu-notwork></fu-notwork>
    <!-- 断网监测 end-->
  </view>
</template>

<script>
  // 高德地图sdk
  import amapFile from '@/libs/amap-wx.js';
  export default {
    computed: {
      // 合并省市区信息字段
      address() {

        if (this.location && this.location.city && !this.ziquName) {
          return this.location.city + this.location.district;
        } else if (this.location && this.location.city && this.ziquName) {
          return this.location.city + this.location.district + '-' + this.ziquName;
        } else {
          return  global.i18n['请授权获取当前位置']
        }

      },
    },
    data() {
      return {
				imgWechatUrl:this.imgWechatUrl,
        CustomBar: this.CustomBar, //标题栏高度
        StatusBar: this.StatusBar, //状态栏高度
        currentIndex: 0, //左侧分类选中项下标
        rember_right_index: 0,
        type: null, // 1 从自取点过来的，2从首页过来的
        selectDistrictItem: {}, //选择的区
        lists: [], //左侧分类数据
        currentList: [], //右侧分类数据
        inviteSome: [],
        ziquName: '',
        ad: [], //广告数据
        myAmapFun: null, // 高德地图实例
        province: global.i18n['河南省'], // 省
        city: global.i18n['郑州市'], //市
        district: '', //区
        provinceCode: '', // 省 code码
        cityCode: '', //市 code码
        districtCode: '', //区 code码
        addressDesc: '', // 详细地址
        location: {}, //省市区
      }
    },
    onShow() {
      let location = this.$store.state.location;
      this.location = location
      console.log(location, 'yij')
      // 初始化高德地图SDK,记得换成自己的key
      this.myAmapFun = new amapFile.AMapWX({
        key: '71e2d1e8fad67225279e724ff7c51e64'
      });
      if (!location) {
        // 自动定位当前地址
        this.autoGetLocation();

      } else {
        this.loadDataOptions();
      }

    },
    onLoad(options) {
      console.log(options, '参数')
      this.type = options.type
    },
    methods: {
      /**
       * @func 定位地址
       */
      getLocation() {
        let _this = this;
        //#ifdef MP-WEIXIN
        uni.getSetting({
          success(res) {
            // 获取设置成功
            console.log(res.authSetting);
            if (!res.authSetting.userLocation) {
              // 如果没开启权限提示打开
              uni.openSetting({
                success(res) {
                  // 打开成功，提示获取权限
                  console.log(res.authSetting);
                  uni.authorize({
                    scope: 'scope.userLocation',
                    success(res) {
                      _this.chooseLocation();
                    },
                    fail(res) {
                      console.log(res);
                      this.$message.info( this.i18n['打开权限失败']);
                    }
                  });
                }
              });
            } else {
              _this.chooseLocation();
            }
          }
        });
        //#endif
        this.chooseLocation();
      },
      /**
       * @func 地图选点
       */
      chooseLocation() {
        let _this = this
        uni.chooseLocation({
          success: (res) => {
            console.log(res, '地图');
            this.myAmapFun.getRegeo({
              location: res.longitude + ',' + res.latitude,
              success: (data) => {
                //成功回调
                console.log('自动定位 SDK回调', data);
                let regeoData = data[0].regeocodeData.addressComponent;
                this.province = regeoData.province;
                this.city = Array.isArray(regeoData.city) && (regeoData.city.length == 0) ? regeoData.province: regeoData.city;
                this.district = regeoData.district;
                this.addressDesc = data[0].desc;
                this.provinceCode = regeoData.adcode.substr(0,2)+'0000';
                this.cityCode = regeoData.adcode.substr(0,4)+'00';
                this.districtCode = regeoData.adcode+'';
                let latitude= data[0].latitude
                let longitude= data[0].longitude
                
                _this.$store.commit('updataLocation', {
                  province: this.province,
                  city: this.city,
                  district:this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                  latitude:latitude,
                  longitude:longitude,
                
                });
                _this.location= {
                  province: this.province,
                  city: this.city,
                  district:this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                  latitude:latitude,
                  longitude:longitude,
                }
                this.loadDataOptions()
              },
              fail: (info) => {
                this.loadDataOptions(); // 搜索方法
                //失败回调
                console.log(info)
              }
            })
          }
        })
      },
      bindChange(e) {
        console.log(e, '滚动的index')
        const val = e.detail.value
        this.rember_right_index = val
        if (this.inviteSome[val] && this.inviteSome[val].deliver_name) {
          this.ziquName = this.inviteSome[val].deliver_name
        }
      },
      /**
       * @description 返回上一页
       */
      back() {
        if (this.type == 1) {
          this.$urouter.redirectTo({
            url: '/pages/address/get-location/index',
            params: {
              type: 1,
              id: this.selectDistrictItem.id,
              name: this.selectDistrictItem.name
            }
          });

        } else {
          uni.navigateBack();
        }
      },
      /**
       * @func 自动定位
       */
      autoGetLocation() {
        let _this = this
        console.log("自动定位");
        uni.getLocation({
          geocode: true,
          success: (adr) => {
            this.myAmapFun.getRegeo({
              location: adr.longitude + ',' + adr.latitude,
              success: (data) => {
                //成功回调
                console.log('自动定位 SDK回调', data);
                let regeoData = data[0].regeocodeData.addressComponent;
                this.province = regeoData.province;
                this.city = Array.isArray(regeoData.city) && (regeoData.city.length == 0) ? regeoData.province :
                  regeoData.city;
                this.district = regeoData.district;
                this.addressDesc = data[0].desc;
                this.provinceCode = regeoData.adcode.substr(0, 2) + '0000';
                this.cityCode = regeoData.adcode.substr(0, 4) + '00';
                this.districtCode = regeoData.adcode + '';

                _this.$store.commit('updataLocation', {
                  province: this.province,
                  city: this.city,
                  district: this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                });
                _this.location = {
                  province: this.province,
                  city: this.city,
                  district: this.district,
                  addressDesc: this.addressDesc,
                  provinceCode: this.provinceCode,
                  cityCode: this.cityCode,
                  districtCode: this.districtCode,
                }
                console.log(_this.location, 444)
                _this.loadDataOptions()
              },
              fail: (info) => {
                _this.loadDataOptions()
                //失败回调
                console.log(info)
              }
            })

          }
        })
      },
      /**
       * 获取左侧分类数
       * @param item 选中分类内容
       * @param index 选中分类下标
       */
      handleSelect(item, index) {
        this.selectDistrictItem = item
        this.currentIndex = index;
        this.ziquName = ''
        this.district = item.name
        const that = this

        this.$api.post(global.apiUrls.getInviteAddress, {
            district_id: item.id
          })
          .then(res => {
            if (res.data.code == 1) {
              console.log('自取点', this.inviteSome)
              this.inviteSome = res.data.data.data || []
              if (that.inviteSome.length == 0) {
                return
              }
              if (that.inviteSome.length >= that.rember_right_index) {
                that.ziquName = that.inviteSome[that.rember_right_index].deliver_name
              } else {
                that.rember_right_index = 0
                that.ziquName = that.inviteSome[0].deliver_name
              }
            } else {
              this.$message.error(res.data.msg);
            }
          })

      },
      /**
       * @description 获取分类数据
       */
      loadDataOptions() {
        const that = this
        this.$api.post(global.apiUrls.getInviteCitys, {
            code: this.location.cityCode || ''
          })
          .then(res => {
            if (res.data.code == 1) {
              let list = res.data.data;
              console.log('分类数据', list, that.location)
              this.lists = list;
              if (that.lists.length > 0 && that.location && that.location.districtCode) {
                that.lists.forEach(function(item, index) {
                  if (item.region_code == that.location.districtCode) {
                    that.handleSelect(item, index)
                    return
                  }
                })
              }
              if (this.lists.length > 0 && !that.location) {
                this.handleSelect(that.lists[0], 0);
              }

              //	默认显示推荐数据
            } else {
              this.$message.error(res.data.msg);
            }
          })
      },

      /**
       * @description 去分类列表页
       * @param cid 商品cid
       */
      navToList(item) {
        console.log(item)
        this.ziquName = item.deliver_name
        // uni.navigateBack();
        // this.$urouter.navigateTo({
        //   url: '/pages/goods/goodslist/goods-search/index',
        //   params: {
        //     cid: cid
        //   }
        // });
      },

    }
  }
</script>

<style lang='scss' scoped>
  .picker-view {
    width: 100%;
    height: 600rpx;

  }

  .picker_item {
    height: 68rpx;
    line-height: 68rpx;
    align-items: center;
    justify-content: center;
    text-align: center;
  }

  
  .block-262 {
    margin: 0 auto;
    width: 326rpx;
    min-width: 326rpx;
    height: 333rpx;
    min-height: 333rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .fu-fs32 {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
  }

  .confirm-type {
    margin-right: 20rpx;
    font-size: 28rpx;
    font-family: PingFang SC;
    font-weight: 400;
    line-height: 40rpx;
    background-color: #FFE26C;
    padding: 10rpx 25rpx;
    border-radius: 25rpx;
    color: #333333;
    opacity: 1;
  }

  .select_location {
    position: fixed;
    height: 200rpx;
    width: 100%;

  }

  .location_icon {
    height: 30rpx;
    width: 30rpx;
    margin-top: 5rpx;
  }

  .cell {
    height: 100rpx;
    font-size: 32upx;
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 100%;
    border-top: 1px solid #f5f5f7;
    border-bottom: 1px solid #f5f5f7;
    background-color: white;

    .title {
      display: inline-block;
      width: 180rpx;
      padding-left: 40rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      color: #999999;
      opacity: 1;
    }

    input {
      flex: 1;
      color: #333;
    }

    .text-area {
      flex: 1;
    }
  }


  // 轮播图 start
  .one-ad {
    height: 150rpx;
    padding: 10rpx 20rpx 10rpx 20rpx;
    border-radius: 20rpx;

    .ad-img {
      width: 100%;
      height: 100%;
      border-radius: 20rpx;
    }
  }

  // 轮播图 end
  .page {
    height: 100vh;

    .content {
      padding-top: 100rpx;
      display: flex;

      //左侧分类 start
      .left {
        width: 168rpx;
        min-width: 168rpx;
        height: 100%;
        background: #ffffff;

        .item-wrap {
          background-color: #F8F8F8;
        }

        .prev-wrap {
          border-radius: 0 0 24rpx 0;
        }

        .next-wrap {
          border-radius: 0 24rpx 0 0;
        }

        .item {
          width: 100%;
          height: 100rpx;
          line-height: 100rpx;
          transition: all 0.2s;
          font-size: 24rpx;

        }

        .item.active {
          background-color: #FFFFFF;
          /* font-size: 32rpx; */
          /* border-radius:24rpx 0 0  24rpx; */
        }

        .item.active1 {
          background-color: #FFFFFF;
          /* font-size: 32rpx;
        border-radius:0 0 0  24rpx; */
        }

        .item.prev {
          border-radius: 0 0 24rpx 0;
        }

        .item.next {
          border-radius: 0 24rpx 0 0;
        }
      }

      //左侧分类 end
    }
  }

  //右侧分类 start
  .right {
    height: 100%;
    display: flex;
    flex-direction: column;
    flex: 1;
    background-color: #FFFFFF;

    .swiper-box {
      padding: 24rpx;

      .swiper {
        height: 180rpx;

        .swiper-item {
          .swiper-item-img {
            width: 100%;
            height: 100%;

            image {
              width: 100%;
              height: 100%;
            }
          }
        }
      }
    }

    .classify-box {
      height: 100%;
      /* padding: 0 24rpx; */

      .block-120 {
        width: 120rpx;
        min-width: 120rpx;
        height: 120rpx;
        min-height: 120rpx;

        image {
          width: 100%;
          height: 100%;
        }
      }
    }
  }

  //右侧分类 end
  //标题栏 start
  .cu-bar .search-form {
    line-height: 52rpx;
    height: 64rpx;
  }

  .text-df {
    justify-content: center;
    align-items: center;

    view {
      width: 120rpx;
      height: 3rpx;
      background: #ccc;
      margin: 0 15rpx;
    }
  }

  .placeholderStyle {
    font-size: 26rpx;
    color: grey;
  }

  //标题栏 end

  .tool-box {
    position: sticky;
    z-index: 999;
    background: #f8f8f8;

    .cu-btn {
      width: 144rpx;
      height: 56rpx;
      border-radius: 56rpx;
      border: 2rpx solid rgba(191, 191, 191, 1);
      background: #fff;
    }
  }
</style>
